<!-- 我的相册 -->
<template>
    <van-nav-bar title="我的相册" :right-text="state.isEdit ? '取消' : '编辑'" left-arrow @click-left="onClickLeft"
        @click-right="onClickRight" />
    <view class="photo-list">
        <view class="photo-main-list">
            <view class="photo-main-list-item" v-for="(item, index) in state.photoList" :key="item.ID">
                <PhotoListItem :itemData="item" :isPerson="true" :userAllPhoto="state.photoList" :userPhotoList="state.photoList.map(o => o.FilePath)"
                    :photoIndex="index" />
                <view class="select-box" v-if="state.isEdit"
                    @click="itemCheck(item)">
                    <img src="@/assets/image/icon01.png" alt="" v-if="item.isCheck">
                    <img src="@/assets/image/icon02.png" alt="" v-else>
                </view>
                <view class="text-box" v-if="photoTypeFn(item)">{{ photoTypeFn(item) }}</view>
            </view>
        </view>
    </view>
    <view class="upload-btn">
        <van-button type="primary" v-if="!state.isEdit" @click="uploadImgFn()">上传照片</van-button>
        <view class="edit-box" v-else>
            <view class="edit-item" @click="updatePhotoState(0)">
                <img src="@/assets/image/icon122.png" alt="">
                <text>普通照片</text>
            </view>
            <view class="edit-item" @click="updatePhotoState(3)">
                <img src="@/assets/image/icon125.png" alt="">
                <text>阅后即焚</text>
            </view>
            <view class="edit-item" @click="updatePhotoState(2)" v-if="state.userInfo.Sex == 0">
                <img src="@/assets/image/icon123.png" alt="">
                <text>红包照片</text>
            </view>
            <view class="edit-item" @click="updatePhotoState(4)">
                <img src="@/assets/image/icon124.png" alt="">
                <text>删除</text>
            </view>
        </view>
    </view>
</template>
    
<script setup>
import { reactive, getCurrentInstance, onMounted } from "vue"
import { getAuthorization, setAuthorization } from "@/utils/auth.js"
import { onLoad } from '@dcloudio/uni-app'
import PhotoListItem from "@/components/photoListItem/index.vue"
import { showLoadingToast, closeToast } from 'vant';

import {
    delUserPhoto, // 批量删除用户照片
} from "@/api/user/index.js"

import {
    uploadAlbum,
    UserPhotoList,
    DisplayState, // 设为普通照片
} from "@/api/person/index.js"

let { proxy } = getCurrentInstance()

const state = reactive({
    show: false,
    isEdit: false,
    photoList: [],
    PageIndex: 1,
    PageSize: 20,
    userInfo: {}
})

onLoad((options) => {
    state.userInfo = JSON.parse(getAuthorization("userInfo"))
    UserPhotoListFn()
})
const onClickLeft = () => history.back();
const onClickRight = () => {
    state.isEdit = !state.isEdit
    state.photoList.forEach(o => o.isCheck = false)
}

const UserPhotoListFn = async () => {
    let id = getAuthorization('userId')
    let params = {
        PageIndex: state.PageIndex,
        PageSize: state.PageSize,
        userID: id
    }
    showLoadingToast({
        duration: 0,
        forbidClick: true,
        message: '',
    });
    let data = await proxy.$get(UserPhotoList, params)
    closeToast();
    if (data.code == 200) {
        data.data.Photos.forEach(o => {
            o.isCheck = false
        })
        state.photoList = state.photoList.concat(data.data.Photos)
    }
}

const photoTypeFn = (item) => {
    let displayObj = {
        2: "红包照片",
        3: "阅后即焚",
        4: "红包阅后即焚",
    }
    let str = displayObj[item.DisplayState]
    str = item.State == 0 ? str : '审核中'
    return str
}

// 选中图片
const itemCheck = (item) => {
    if(item.State != 0){
        uni.showToast({
            title:"审核中，不能操作",
            icon:"none",
        })
        return
    }
    return state.isEdit ? item.isCheck = !item.isCheck : item.isCheck == item.isCheck 
}

// 批量删除用户照片
const delUserPhotoFn = async (IDs) => {
    let params = {
        "photoIDs": IDs,
        "displayState": 0
    }
    try {
        uni.showLoading({
            icon: "none"
        })
        let data = await proxy.$put(delUserPhoto, params)
        state.photoList = state.photoList.filter(o => !IDs.includes(o.ID))
        uni.hideLoading()
        if (!data.data) {
            uni.showToast({
                icon: "none",
                title: data.message
            })
        }
    } catch (error) {
        uni.hideLoading()
        uni.showToast({
            icon: "none",
            title: error.message
        })
    }
}

// 设为普通照片
const DisplayStateFn = async (type) => {
    let params = { "photoIDs": state.photoList.filter(o => o.isCheck).map(o => o.ID), "displayState": type }
    let data = await proxy.$put(DisplayState, params)
    state.photoList = []
    UserPhotoListFn()
}

// 设置照片查看状态
const updatePhotoState = async (type) => {
    let IDs = state.photoList.filter(o => o.isCheck).map(o => o.ID)
    if (IDs.length == 0) {
        uni.showToast({
            title: "请选择要操作的照片",
            icon: "none"
        })
        return
    }
    if (type == 0 || type == 2 || type == 3) {
        DisplayStateFn(type)
    }
    if (type == 4) delUserPhotoFn(IDs)
}

// 上传照片
const uploadImgFn = async () => {
    uni.chooseImage({
        count: 6, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera', 'album'], //从相册选择
        success: function (res) {
            let tokenObj = getAuthorization("token") ? JSON.parse(getAuthorization("token")) : ""
            let token = tokenObj.AccessToken
            showLoadingToast({
                duration: 0,
                forbidClick: true,
                message: '图片上传中',
            });
            uni.uploadFile({
                url: '/api/app/api/G/user-heibai/v1/Files', //仅为示例，非真实的接口地址
                files: res.tempFiles.map(o => {
                    return {
                        name: o.name,
                        file: o,
                        uri: o.path
                    }
                }),
                name: 'file',
                header: {
                    "Authorization": "Bearer " + token
                },
                formData: {
                    'groupCode': '99999999'
                },
                success: (uploadFileRes) => {
                    let data = JSON.parse(uploadFileRes.data)
                    if (data.code == 200) {
                        uploadAlbumFn(data)
                    }
                },
                fail: (error) => {
                    uni.showToast({
                        title: error.message
                    })
                },
                complete: () => {
                    closeToast();
                }
            });
        }
    });
}

// 上传到相册
const uploadAlbumFn = async (dataImg) => {
    let params = {
        "photos": dataImg.data.map(o => {
            return {
                fileID: o.ID
            }
        })
    }
    let data = await proxy.$post(uploadAlbum(getAuthorization('userId')), params)
    if (data.code == 200) {
        uni.showToast({
            title: "图片上传成功",
            icon: "none"
        })
        state.PageIndex = 1
        state.photoList = []
        UserPhotoListFn()
    }
}

</script>
    
<style lang="scss" scoped>
.photo-list {
    padding-bottom: 180rpx;
}

.photo-main-list {
    display: flex;
    flex-wrap: wrap;

    .photo-main-list-item {
        width: calc(33.33% - 40rpx);
        margin: 30rpx 0 0 30rpx;
        position: relative;
        border-radius: 12rpx;
        overflow: hidden;

        .select-box {
            position: absolute;
            right: 10rpx;
            top: 10rpx;
            width: 40rpx;

            img {
                width: 40rpx;
            }
        }

        .text-box {
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            text-align: center;
            color: #fff;
            height: 60rpx;
            line-height: 60rpx;
        }
    }
}

.upload-btn {
    position: fixed;
    bottom: 0;
    padding-bottom: 40rpx;
    width: 100%;
    background: #fff;
    z-index: 999;

    .van-button {
        width: calc(100% - 60rpx);
        margin-left: 30rpx;
        height: 100rpx;
        font-size: 36rpx;
    }
}

.edit-box {
    display: flex;
    justify-content: space-between;
    text-align: center;
    border-top: 1px solid #ccc;
    padding-top: 20rpx;

    .edit-item {
        width: 25%;
    }

    img {
        width: 40rpx;
    }

    text {
        display: block;
    }
}
</style>
    